using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Threading;
using CoreLab.Oracle;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.ETL
{
    /// <summary></summary>
    public class BFileDownloadWorker:IWorker
    {
        private Thread _WorkerThread;
        private BFileDownloadInstruction _Instruction;
        private BFileDownloadOutput _Output;
        private Guid _TicketID;
        private RunContext _Context;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }

        /// <summary></summary>
        public Thread WorkerThread
        {
            get { return _WorkerThread; }
        }
        /// <summary></summary>
        public InstructionBase Instruction
        {
            get { return _Instruction; }
        }
        /// <summary></summary>
        public ResultBase Output
        {
            get { return this._Output; }
        }
        /// <summary></summary>
        public Type ComponentType
        {
            get { return typeof(BFileDownloadComponent); }
        }
        /// <summary></summary>
        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }
        /// <summary></summary>
        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._TicketID = ticketGuid;
            this._Instruction = (BFileDownloadInstruction) request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }
        /// <summary></summary>
        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._Context = context;
            this._TicketID = ticketGuid;
            this._Instruction = (BFileDownloadInstruction) request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }
        /// <summary></summary>
        public void DoWork()
        {
            if (this.WorkerStartedEvent != null)
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);

            this._WorkerThread = Thread.CurrentThread;
            this.DownloadBFile();
        }
        /// <summary></summary>
        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);

            this._WorkerThread = new Thread(new ThreadStart(this.DownloadBFile));
            this._WorkerThread.Start();
        }
        /// <summary></summary>
        public void CancelWork()
        {
            if(this._WorkerThread !=null)
            {
                if(this._WorkerThread.IsAlive)
                {
                    this._WorkerThread.Abort();

                    if(this.WorkerCancelledEvent !=null)
                    {
                        this.WorkerCancelledEvent(this._TicketID, this.GetType(), this._Instruction);
                    }
                }
            }
        }

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        #region bfile download
        private void DownloadBFile()
        {
            IDbConnection conn;
            if (this._Instruction.DbProvider == DataProviderType.Oracle)
            {
                conn = new OracleConnection(this._Instruction.ConnStr);
            }
            else
            {
                conn = new SqlConnection(this._Instruction.ConnStr);
            }
            if (string.IsNullOrEmpty(this._Instruction.LogFilePath))
            {
                this._Instruction.LogFilePath =
                    Path.Combine(this._Instruction.DownloadToFolder, "BfileDownload.log");
            }
            if (File.Exists(this._Instruction.LogFilePath))
            {
                File.Delete(this._Instruction.LogFilePath);
            }
            if (string.IsNullOrEmpty(this._Instruction.ErrorFilePath))
            {
                this._Instruction.ErrorFilePath =
                    Path.Combine(this._Instruction.DownloadToFolder, "BFileDownload.err");
            }
            if (File.Exists(this._Instruction.ErrorFilePath))
            {
                File.Delete(this._Instruction.ErrorFilePath);
            }
            StreamWriter logWriter = new StreamWriter(this._Instruction.LogFilePath);
            StreamWriter errWriter = new StreamWriter(this._Instruction.ErrorFilePath);
            try
            {
                int totalRecordToScan =
                    DbUtil.GetTableRecordCount(this._Instruction.DbProvider, this._Instruction.ConnStr,
                                               this._Instruction.SelectStatement);
                if(totalRecordToScan ==0)
                {
                    totalRecordToScan = 100;
                }
                conn.Open();
                IDbCommand cmd = conn.CreateCommand();
                cmd.CommandText = this._Instruction.SelectStatement;
                cmd.CommandTimeout = 0;
                int bfileIdx = -1;
                IDataReader reader = cmd.ExecuteReader();
                bfileIdx = reader.GetOrdinal(this._Instruction.BFileField);
                int totalFileScanned = 0;
                int recordsDownloaded = 0;
                while(reader.Read())
                {
                    string fileName = string.Empty;
                    try
                    {
                        fileName = reader[this._Instruction.FileNameField].ToString();
                        if(string.IsNullOrEmpty(fileName))
                        {
                            throw new Exception("FileName field is empty");
                        }
                        fileName = this.FormatFileName(fileName, this._Instruction.FileNameFormat);
                        string tgtFilePath = Path.Combine(this._Instruction.DownloadToFolder, fileName);
                        if (!File.Exists(tgtFilePath))
                        {
                            byte[] contents = null;
                            if (this._Instruction.DbProvider == DataProviderType.Oracle)
                            {
                                OracleBFile oraBFile = ((OracleDataReader) reader).GetOracleBFile(bfileIdx);
                                oraBFile.OpenFile();
                                long fileSize = oraBFile.Length;
                                contents = new byte[fileSize];
                                oraBFile.Read(contents, 0, contents.Length);
                                oraBFile.Close();
                            }
                            else
                            {
                                contents = (byte[]) reader.GetValue(bfileIdx);
                            }
                            this.SaveBFile(this._Instruction.DownloadToFolder, fileName, contents);
                            recordsDownloaded++;
                        }
                        totalFileScanned++;
                        logWriter.WriteLine(fileName);
                        if (this.WorkerStatusChangedEvent != null && totalFileScanned % 10 == 0)
                        {
                            int percent = (totalFileScanned*100)/totalRecordToScan;
                            string msg =
                                string.Format("Scanning #{0} of #{1} records, #{2} downloaded", totalFileScanned,
                                              totalRecordToScan, recordsDownloaded);
                            this.WorkerStatusChangedEvent(this._TicketID, this.GetType(), this._Instruction,
                                this.WorkflowName, this.ComponentName, msg,
                                                          percent);
                            logWriter.Flush();
                        }
                    }
                    catch(Exception ex1)
                    {
                        if(!string.IsNullOrEmpty(fileName))
                        {
                            errWriter.WriteLine("Unable to read: " + ex1.ToString());
                        }
                        else
                        {
                            errWriter.WriteLine("Unable to get BFile {0}: {1}",
                                                (string.IsNullOrEmpty(fileName) ? string.Empty : fileName),
                                                ex1.ToString());
                        }
                        errWriter.Flush();
                    }
                }
                reader.Close();
                this._Output = new BFileDownloadOutput(this._Instruction.OwnerComponentID, this._TicketID, recordsDownloaded, this._Instruction.LogFilePath, this._Instruction.LogFilePath);
                    
                if(this.WorkerFinishedEvent !=null)
                {
                    this.WorkerFinishedEvent(this._TicketID, this.GetType(), this._Instruction, this._Output);
                }
            }
            catch(Exception ex)
            {
                if(this.WorkerErredEvent !=null)
                {
                    this.WorkerErredEvent(this._TicketID, this.GetType(), this._Instruction, ex.ToString(),true);
                }
            }
            finally
            {
                logWriter.Close();
                errWriter.Close();
                conn.Close();
            }
        }

        private string FormatFileName(string fileName, string format)
        {
            if(!string.IsNullOrEmpty(format))
            {
                if(format.IndexOf("{0}")>=0)
                {
                    fileName = format.Replace("{0}", fileName);
                }
            }
            return fileName;
        }

        private void SaveBFile(string tgtFolder, string tgtFileName, byte[] contents)
        {
            try
            {
                string tgtFilePath = Path.Combine(tgtFolder, tgtFileName);
                if(File.Exists(tgtFilePath))
                {
                    File.Delete(tgtFilePath);
                }
                FileStream inFile=new FileStream(tgtFilePath,FileMode.Create);
                inFile.Write(contents,0,contents.Length);
                inFile.Flush();
                inFile.Close();
            }
            catch(Exception ex)
            {
                if(this.WorkerErredEvent !=null)
                {
                    this.WorkerErredEvent(this._TicketID, this.GetType(), this._Instruction, ex.ToString(),true);
                }
            }
        }
        #endregion
    }
}
